package com.gitee.hermer.engine.jars.core.autoconfigure.condition;

import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.ClassUtils;

import com.gitee.hermer.engine.jars.core.autoconfigure.annotate.ConditionalOnEngineApplication;
import com.gitee.hermer.engine.jars.core.domain.EngineConstant;

@Order(Ordered.HIGHEST_PRECEDENCE + 20)
public class OnEngineApplicationCondition extends EngineJarsCondition{

	@Override
	public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
		boolean required = metadata
				.isAnnotated(ConditionalOnEngineApplication.class.getName());
		ConditionOutcome outcome = isEngineApplication(context, metadata, required);
		if (required && !outcome.isMatch()) {
			return ConditionOutcome.noMatch(outcome.getConditionMessage());
		}
		if (!required && outcome.isMatch()) {
			return ConditionOutcome.noMatch(outcome.getConditionMessage());
		}
		return ConditionOutcome.match(outcome.getConditionMessage());
	}

	private ConditionOutcome isEngineApplication(ConditionContext context,
			AnnotatedTypeMetadata metadata, boolean required) {
		ConditionMessage.Builder message = ConditionMessage.forCondition(
				ConditionalOnEngineApplication.class, required ? "(required)" : "");
		if (EngineConstant.CLASS_ENGINE_APP_CLASS_LOADER == null || (!com.gitee.hermer.boot.jee.commons.reflect.ClassUtils.isAssignable(
				EngineConstant.CLASS_ENGINE_APP_CLASS_LOADER, context.getClassLoader().getClass()))) {
			return ConditionOutcome
					.noMatch(message.didNotFind("not match engine classloader").atAll());
		}
		if(ClassUtils.isPresent(EngineConstant.CLASS_NAME_ENGINE_CONTEXT_EVNIRONMENT, context.getClassLoader())){
			return ConditionOutcome.match(message.foundExactly("Engine Environment"));
		}
		return ConditionOutcome.noMatch(message.because("not a engine application"));
	}

}
